package school.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import school.domain.User;
import school.support.util.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class BaseController {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpSession session;

    protected String refresh() {
        return "redirect:" + request.getHeader("Referer");
    }

    protected boolean isAdmin() {
        Object sessionUser = session.getAttribute("sessionAdmin");
        if(sessionUser !=null){
            return true;
        }
        return false;
    }

    protected boolean isLogin() {
        Object sessionUser = session.getAttribute("sessionUser");
        return sessionUser != null;
    }

    /**
     * 登录用户
     * @return
     */
    protected User loginUser() {
        Object sessionUser = session.getAttribute("sessionUser");
        return (User) sessionUser;
    }

    /**
     * 上传文件路径
     *
     * @return
     */
    protected String uploadPath() {
        return request.getServletContext().getRealPath("/data/") + "/";
    }

    /**
     * 保存文件
     *
     * @param file
     * @return
     */
    protected String saveFile(MultipartFile file) {
        return "data/"+FileUtils.saveFile(file, uploadPath());
    }
}
